package userFileModuleApi

import (
	"KumquatDrivesServices/StorageEngine"
	"KumquatDrivesServices/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

func (UserFileModuleApi) GetCoverImage(c *gin.Context) {
	filePath := c.Param("filePath")
	userIDStr, fileName, err := parseFilePath(filePath)
	if err != nil {
		logrus.Errorf("parseFilePath err:%v", err)
		c.JSON(400, gin.H{"error": "Invalid file path"})
	}
	var userModel model.UserModel
	userID, AtoiErr := strconv.ParseInt(userIDStr, 10, 64)
	if AtoiErr != nil {
		logrus.Errorf("Atoi err: %v", AtoiErr)
		c.JSON(400, gin.H{"error": "Invalid file path"})
	}
	userModel.ID = model.SnowflakeIdType(userID)
	userInfo, GetCacheUserInfoErr := userModel.GetCacheUserInfo()
	if GetCacheUserInfoErr != nil {
		logrus.Errorf("GetCacheUserInfoErr: %v", GetCacheUserInfoErr)
		c.JSON(400, gin.H{"error": "未授权访问"})
		return
	}
	data, GetCoverImageErr := StorageEngine.Engine.GetCoverImage(userInfo.UserEmail, fileName)
	if GetCoverImageErr != nil {
		if errors.Is(GetCoverImageErr, StorageEngine.ErrFileNotExistErr) {
			c.JSON(404, gin.H{"error": "未找到封面图片"})
			return
		}
		logrus.Errorf("GetCoverImage err: %v", GetCoverImageErr)
		c.JSON(500, gin.H{"error": "服务器内部错误"})
		return
	}
	c.Header("cache-control", "max-age=3600; preload")
	c.Data(200, "Image/jpeg", data)
}
